package com.njcb.ams.support.exception;

import com.njcb.ams.factory.comm.DataBus;
import com.njcb.ams.factory.domain.AppContext;
import com.njcb.ams.portal.SysBaseDefine;
import com.njcb.ams.repository.dao.SysExceptionLogDAO;
import com.njcb.ams.repository.entity.ExceptionLog;
import com.njcb.ams.repository.entity.SysTradeLog;
import com.njcb.ams.util.AmsDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author liuyanlong
 */
public class ExceptionWriter {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionWriter.class);

    public static void writeLog(String errorCode, String errorMsg, Throwable t) {
        if (null == DataBus.getAttribute(ExceptionUtil.EXCEPTION_STACK_TRACE) || !DataBus.getAttribute(ExceptionUtil.EXCEPTION_STACK_TRACE, boolean.class)) {
            DataBus.setAttribute(ExceptionUtil.EXCEPTION_STACK_TRACE, true);
            logger.error(errorCode + "[" + errorMsg + "]", t);
        }
        SysTradeLog tradeLog = DataBus.getAttribute(SysBaseDefine.GLOBALINFO_SYSTRADELOG, SysTradeLog.class);
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw, true));
        String stackString = sw.getBuffer().toString();
        ExceptionLog writerBean = new ExceptionLog();
        writerBean.setErrorCode(errorCode);
        writerBean.setErrorMsg(errorMsg);
        writerBean.setErrorDate(AmsDateUtils.getCurrentDate8());
        writerBean.setErrorTime(AmsDateUtils.getCurrentTime6());
        writerBean.setUserInfo(DataBus.getLoginName());
        writerBean.setStackTrace(stackString);
        if(null != tradeLog){
            writerBean.setTransSeq(tradeLog.getTransSeq());
        }
        SysExceptionLogDAO exceptionLogDAO = AppContext.getBean(SysExceptionLogDAO.class);
        try {
            exceptionLogDAO.insert(writerBean);
        } catch (Throwable logt) {
            logger.error(logt.getMessage(), logt);
        }
    }
}